<?php
/**
 * Created by PhpStorm.
 * User: liandne
 * Date: 2016/12/12
 * Time: 下午5:06
 */

namespace App\Http\Controllers\Api;


use App\Activity;
use App\Department;
use App\DocHug;
use App\Doctors;
use App\DoctorTime;
use App\DoctorWeek;
use App\Exceptions\NotFoundException;
use App\Exceptions\SecurityException;
use App\Exceptions\YiLiaoException;
use App\Hospital;
use App\Http\Requests\BespokeRequest;
use App\Orders;
use App\Packages;
use App\Services\Tools;
use App\Services\UserManager;
use App\User;
use App\UserActivity;
use App\UserActivityGuest;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class YiLiaoController extends ApiController
{

    /**
     * 提交套餐接口
     * @param Guard $guard
     * @param BespokeRequest $request
     * @throws SecurityException
     */
    public function submitPackageBespoke(Guard $guard,BespokeRequest $request){
        $user = UserManager::isLogin($request);
        if(!$user) {
            throw new SecurityException(SecurityException::LoginFirst);
        }

//        $user = User::find(1);
        $name = $request->get('name');
        $born = $request->get('born');
        $phone = $request->get('phone');
        $be_time = $request->get('time');

        $pack_id = $request->get('pack_id');

        $package = Packages::find($pack_id);
        $connect = $package->getConnection();
        $connect->beginTransaction();
        $order = new Orders();
        $order->user_id = $user->id;
        $order->package_id = $pack_id;
        $order->order_num = Tools::makeBillNum();
        $order->order_price = $package->bespeak_fee + $package->consulting_fee;
        $order->type = 'package';
        $order->patient_birth = $born;
        $order->patient_name = $name;
        $order->patient_phone = $phone;
        $order->bespoke_time = $be_time;
        $isSeccess = $order->save();

        if ($isSeccess){
            $connect->commit();
            return $this->buildResponse(trans('提交预约成功'),$order);
            
        }
        else{
            $connect->rollBack();
            throw new SecurityException(SecurityException::NetWorkError);
        }
        
    }

    /**
     * 提交挂号接口
     * @param Guard $guard
     * @param BespokeRequest $request
     * @throws SecurityException
     */
    public function submitDoctorBespoke(Guard $guard,Request $request){
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user    = $guard->user();
        $phone   = Input::get('phone');
        $be_time = Input::get('time');
        $be_slot = Input::get('slot');
        $doc_id  = Input::get('doc_id');
        $type    = !is_null(Input::get('type'))?Input::get('type'):'appoint';

        /** @var Doctors $thatDoc */
        $thatDoc = Doctors::whereUserId($doc_id)->first();
        if(!$thatDoc)
            throw new NotFoundException(NotFoundException::DataNotFound);

        $week_time = Tools::getWeekNum(strtotime($be_time));

        /** @var DoctorTime $thatDocHug */
        $thatDocHug = DoctorWeek::whereUserId($thatDoc->user_id)->whereWeek($week_time)->whereType($type)->first();
        if(!$thatDocHug)
            throw new YiLiaoException(YiLiaoException::CanSelectTheTime);

        if($be_slot == 'am'){
            if($thatDocHug->am == 0){
                throw new YiLiaoException(YiLiaoException::CanSelectTheTime);
            }
        }else if($be_slot == 'pm'){
            if($thatDocHug->pm == 0){
                throw new YiLiaoException(YiLiaoException::CanSelectTheTime);
            }
        }

        $amount = 0;
        if($type == "appoint")
            $amount = $thatDoc->fee;
        else
            $amount = $thatDoc->fee_face;

        $order                = new Orders();
        $connect              = $order->getConnection();
        $connect->beginTransaction();
        $order->user_id       = $user->id;
        $order->doctor_id     = $doc_id;
        $order->order_num     = Tools::makeBillNum();
        $order->order_price   = $amount;
        $order->type          = $type;
        $order->patient_name  = $user->userInfo->realname;
        $order->patient_phone = $phone;
        $order->bespoke_time  = $be_time;
        $order->bespoke_slot  = $be_slot;
        $order->hospital_id   = $thatDoc->hospital_id;
        $isSeccess            = $order->save();

        if ($isSeccess){
            $connect->commit();
            return $this->buildResponse(trans('提交预约成功'),$order);
        }
        else{
            $connect->rollBack();
            throw new SecurityException(SecurityException::NetWorkError);
        }

    }

    public function getDoctorHug($doctor_data){
        $data = explode('_',$doctor_data);
        $doctor_id = $data[0];
        $time = $data[1];
        $doctor = Doctors::whereId($doctor_id)->whereIsWork(1)->first();
        $hug = $doctor->hug()->where('hugh_date','=',$time)->get();
        return $this->buildResponse(trans('获取休息日期成功'),$hug);
    }

    public function appendPackages($page){
        $page = $page * 10;
        $data = Packages::whereIsOff(0)->whereIsPersonal(0)->skip($page)->take(10)->orderBy('created_at','desc')->get();
        $packages['data'] = $data;
        $packages['count'] = count($data);
        return $this->buildResponse(trans('数据'),$packages);
    }

    public function appendDoctors($page){
        $page = $page * 10;
        $data = Doctors::whereIsWork(1)->skip($page)->take(10)->orderBy('created_at','desc')->get();
        $doctors['data'] = $data;
        $doctors['count'] = count($data);
        return $this->buildResponse(trans('医生数据'),$doctors);
    }

    public function setDoctorHug(){
        $id   = Input::get('id');
        $date = Input::get('date');
        $hugs = Input::get('hugs');

        $thatHugs = DocHug::whereDocId($id)->whereHughDate($date)->get();

        $hasHugs = array();
        foreach($thatHugs as $hug){
            if($hug){
                array_push($hasHugs,$hug->hugh_slot);
            }
        }

        if(count($hugs)>0){
            $newHugs = array_diff($hugs,$hasHugs);

            $oldHugs = array_diff($hasHugs,$hugs);

            foreach($newHugs as $newHug){
                $newHugModel = new DocHug();
                $newHugModel->doc_id = $id;
                $newHugModel->hugh_date = $date;
                $newHugModel->hugh_slot = $newHug;
                $newHugModel->save();
            }

            foreach($oldHugs as $oldHug){
                /** @var DocHug $oldHugModel */
                $oldHugModel = DocHug::whereDocId($id)->whereHughDate($date)->whereHughSlot($oldHug)->first();

                if($oldHugModel)
                    $oldHugModel->delete();
            }
        }else{
            foreach($hasHugs as $Hug){
                /** @var DocHug $oldHugModel */
                $oldHugModel = DocHug::whereDocId($id)->whereHughDate($date)->whereHughSlot($Hug)->first();

                if($oldHugModel)
                    $oldHugModel->delete();
            }
        }
        return $this->buildResponse(trans('更新成功'));
    }
    
    public function shangJia($id){
        $package = Packages::find($id);
        $off = '';
        switch ($package->is_off){
            case '0':
                $off = 1;
                break;
            case '1':
                $off = 0;
                break;
            default:
                break;
        }
        $package->is_off = $off;
        $package->save();
        return $this->buildResponse(trans('上下架成功'),$package);
    }

    public function deletePackage($id){

        $package = Packages::whereId($id)->delete();

        return $this->buildResponse(trans('删除成功'),$package);
    }

    public function addPackages(Guard $guard){

        $id           = !is_null(Input::get('id')) ? Input::get('id') : 0;
        $name         = Input::get('name');
        $consult_fee  = Input::get('consult_fee');
        $photo        = Input::get('photo');
        $subject      = Input::get('subject');
        $bespeak_fee  = Input::get('bespeak_fee');
        $detail       = Input::get('detail');
        $is_off       = Input::get('is_off');

//        if($guard->guest())
//            throw new SecurityException(SecurityException::LoginFirst);
//
//        /** @var User $admin */
//        $admin = $guard->user();
//        if((int)$admin->role < 3)
//            throw new SecurityException(SecurityException::NoPermission);

        $package = Packages::find($id);

        if(!$package)
            $package = new Packages();

        if(!is_null($name))$package->pak_name = $name;
        if(!is_null($consult_fee))$package->consulting_fee = $consult_fee;
        if(!is_null($photo))$package->pak_img = $photo;
        if(!is_null($subject))$package->pak_subject = $subject;
        if(!is_null($bespeak_fee))$package->bespeak_fee = $bespeak_fee;
        if(!is_null($detail))$package->pak_detail = $detail;
        if(!is_null($is_off))$package->is_off = $is_off;

        $package->save();

        return $this->buildResponse(trans('添加成功'),$package);
    }

    public function confimOrder(Guard $guard){
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();

        if((int)$user->role == 0)
            throw new SecurityException(SecurityException::NoPermission);

        $id = Input::get('id');

        /** @var Orders $thatOrder */
        $thatOrder = Orders::find($id);

        if(!$thatOrder)
            throw new NotFoundException(NotFoundException::OrderNotFound);

        $thatOrder->status = 1;
        $thatOrder->save();

        /** @var Doctors $thatDoc */
        $thatDoc = Doctors::whereUserId($thatOrder->doctor_id)->first();
        if(!$thatDoc){
            throw new NotFoundException(NotFoundException::DataNotFound);
        }

        $thatDoc->has_amount = (float)$thatDoc->has_amount + (float)$thatOrder->order_price;
        $thatDoc->save();

        return $this->buildResponse(trans('设置成功'),$thatOrder);
    }

    public function getActivityRegistrationFee(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityId       = Input::get("activity_id");
        $is_accommodation = Input::get('is_accommodation') ? Input::get('is_accommodation') : 0;

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '活动已下架']);

        $cost = $thisActivity->cost;

        $accommodation_cost = $thisActivity->accommodation_cost;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $cost,'accommodation_cost' => $accommodation_cost]);
    }

    public function getDoctorInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityId       = Input::get("activity_id");

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '活动已下架']);

        $hospitalId = 0;
        $hospitalName = '';
        $depId = 0;
        $depName = '';
        $sex = 0;
        $realName = '';
        $phone = '';
        $station = '';
        $noUpdate = 0;

        /** @var Doctors $thisDoctor */
        $thisDoctor = Doctors::whereUserId($user->id)->first();
        if($thisDoctor){
            $hospital = Hospital::whereId($thisDoctor->hospital_id)->first();
            if($hospital){
                $hospitalId = $hospital->id;
                $hospitalName = $hospital->name;
            }

            $thisDep = Department::whereId($thisDoctor->dep_id)->first();
            if($thisDep){
                $depId = $thisDep->id;
                $depName = $thisDep->dep_name;
            }

            $sex = $thisDoctor->sexual;
            $realName = $thisDoctor->doc_name;
            $phone   = $thisDoctor->phone;
            $station = $thisDoctor->station;

            if($thisDoctor->is_work == 1){
                $noUpdate = 1;
            }
        }

        $arr = [
            'hospital_id' => $hospitalId,
            'hospital_name' => $hospitalName,
            'dep_id' => $depId,
            'dep_name' => $depName,
            'sex' => $sex,
            'real_name' => $realName,
            'phone' => $phone,
            'station' => $station,
            'no_update' => $noUpdate
        ];

        return response()->json(['level' => 'success','message' => '获取成功','data' => $arr]);
    }

    public function getAllHospital(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user){
            if($guard->guest())
                return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

            /** @var User $user */
            $user = $guard->user();
        }

        $allHospital = Hospital::select('id','name')->orderBy('sort','asc')->orderBy('created_at','desc')->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $allHospital]);
    }

    public function getAllDep(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user){
            if($guard->guest())
                return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

            /** @var User $user */
            $user = $guard->user();
        }

        $hospital_id = !is_null($request->get('hospital_id')) ? $request->get('hospital_id') : 0;

        if($hospital_id == '' || $hospital_id == 0){
            return response()->json(['level' => 'error','message' => '请先选择医院']);
        }

        $allDep = Department::whereHospitalId($hospital_id)->select('id','dep_name')->orderBy('created_at','desc')->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $allDep]);
    }

    /**
     * 会议报名接口
     * @param Guard $guard
     * @param BespokeRequest $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws SecurityException
     */
    public function buildActivityOrder(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user){
            if($guard->guest())
                return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

            /** @var User $user */
            $user = $guard->user();
        }



        $activityId       = Input::get("activity_id");
        $realName         = Input::get('real_name');
        $phone            = Input::get('phone');
        $wechat           = Input::get('wechat');
        $is_accommodation = Input::get('is_accommodation') ? Input::get('is_accommodation') : 0;
        $station          = Input::get('station');
        $hospitalId       = Input::get('hospital_id') ? Input::get('hospital_id') : 0;
        $depId            = Input::get('dep_id') ? Input::get('dep_id') : 0;
        $sex              = Input::get('sex') ? Input::get('sex') : 0;

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '活动已下架']);

        if(strtotime($thisActivity->start_time) <= time())
            return response()->json(['level' => 'error','message' => '报名已停止']);

        if(strtotime($thisActivity->end_time) <= time())
            return response()->json(['level' => 'error','message' => '活动已结束']);

        $isJoinActivity = UserActivity::whereUserId($user->id)->whereActivityId($thisActivity->id)->whereStatus(1)->first();
        if($isJoinActivity)
            return response()->json(['level' => 'error','message' => '您已经报名过了']);

        $joinNum = UserActivity::whereActivityId($thisActivity->id)->whereStatus(1)->count();
        if($thisActivity->max_join_num <= $joinNum)
            return response()->json(['level' => 'error','message' => '活动参与人数已满']);

        if(is_null($realName) || $realName == '')
            return response()->json(['level' => 'error','message' => '请填写姓名']);

        if(is_null($phone) || $phone == '')
            return response()->json(['level' => 'error','message' => '请填写手机号']);

        if(!preg_match("/^1[345789]{1}\d{9}$/",$phone))
            return response()->json(['level' => 'error','message' => '手机号格式不正确']);

        if(is_null($hospitalId) || $hospitalId == '')
            return response()->json(['level' => 'error','message' => '请填写医院']);

        if(is_null($depId) || $depId == '')
            return response()->json(['level' => 'error','message' => '请填写科室']);

        if(is_null($station) || $station == '')
            return response()->json(['level' => 'error','message' => '请填写职称']);

        $buildOrder = new Orders();
        $buildOrder->user_id       = $user->id;
        $buildOrder->order_num     = Tools::makeBillNum();
        $buildOrder->activity_id   = $thisActivity->id;

        $cost = $thisActivity->cost;

        if($is_accommodation == 1){
            $cost = $cost + $thisActivity->accommodation_cost;
        }

        $buildOrder->order_price = $cost;

        $buildOrder->type          = 'sign_up';
        $buildOrder->status        = 0;
        $buildOrder->save();

        $buildJoinActivity = new UserActivity();
        $buildJoinActivity->user_id                                               = $user->id;
        $buildJoinActivity->activity_id                                           = $thisActivity->id;
        $buildJoinActivity->real_name                                             = $realName;
        $buildJoinActivity->phone                                                 = $phone;
        $buildJoinActivity->wechat                                                = $wechat;
        $buildJoinActivity->order_num                                             = $buildOrder->order_num;
        $buildJoinActivity->station                                               = $station;
        $buildJoinActivity->hospital                                              = $hospitalId;
        $buildJoinActivity->dep                                                   = $depId;
        $buildJoinActivity->sexual                                                = $sex;
        $buildJoinActivity->save();

        return response()->json(['level' => 'success','message' => '订单生成成功','data' => $buildOrder]);
    }
}